package com.xky.controller;

import com.xky.pojo.Book;
import com.xky.pojo.Borrower;
import com.xky.pojo.Result;
import com.xky.service.BookService;
import com.xky.service.BorrowerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 借阅人员类
 */
@Slf4j
@RestController
@RequestMapping("/borrower")
public class BorrowerController {

    @Autowired
    private BorrowerService borrowerService;

    @Autowired
    private BookService bookService;

    /**
     * 借书人员登记
     * @param borrower 借阅信息
     * @return 处理结果
     */
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public Result addBorrower(@RequestBody Borrower borrower) {
        log.info("收到借书请求: {}", borrower);
        
        try {
            // 1. 参数校验
            if (borrower.getBookCode() == null) {
                log.error("图书编号为空");
                return Result.error("图书编号不能为空");
            }
            if (borrower.getBorrowerName() == null || borrower.getBorrowerName().trim().isEmpty()) {
                log.error("借阅人姓名为空");
                return Result.error("借阅人姓名不能为空");
            }
            if (borrower.getBorrowerAddress() == null || borrower.getBorrowerAddress().trim().isEmpty()) {
                log.error("借阅人地址为空");
                return Result.error("借阅人地址不能为空");
            }
            if (borrower.getBookName() == null || borrower.getBookName().isEmpty()) {
                log.error("图书名为空");
                return Result.error("图书名不能为空");
            }

            // 2. 验证图书是否存在
            Book book = bookService.selectByCode(borrower.getBookCode());
            if (book == null) {
                log.error("图书不存在，编号: {}", borrower.getBookCode());
                return Result.error("该图书不存在");
            }

            // 3. 保存借阅记录
            log.info("开始保存借阅记录: {}", borrower);
            borrowerService.addBorrower(borrower);
            log.info("借阅记录保存成功");
            
            // 4. 修改图书的状态
            log.info("开始修改已借出图书的状态，编号: {}", borrower.getBookCode());
            bookService.updateByCode(book, borrower.getBookCode());
            log.info("图书状态修改成功");
            
            return Result.success();
        } catch (Exception e) {
            log.error("借书操作失败: {}", e.getMessage(), e);
            // 手动标记事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("借书操作失败: " + e.getMessage());
        }
    }

    /**
     * 归还图书
     * @param borrower 借阅信息
     * @return 处理结果
     */
    @PutMapping("/return")
    @Transactional(rollbackFor = Exception.class)
    public Result returnBook(@RequestBody Borrower borrower) {
        try {
            log.info("收到归还图书请求 - 借阅人信息: {}", borrower);
            
            // 1. 基础参数校验
            if (borrower == null) {
                log.error("借阅人信息为空");
                return Result.error("借阅人信息不能为空");
            }
            if (borrower.getBookCode() == null) {
                log.error("图书编号为空");
                return Result.error("图书编号不能为空");
            }
            if (borrower.getBorrowerName() == null || borrower.getBorrowerName().trim().isEmpty()) {
                log.error("借阅人姓名为空");
                return Result.error("借阅人姓名不能为空");
            }

            // 2. 验证借阅记录是否存在
            Borrower existingBorrower = borrowerService.getBorrowerByNo(borrower.getBookCode());
            if (existingBorrower == null) {
                log.error("借阅记录不存在 - 图书编号: {}", borrower.getBookCode());
                return Result.error("该图书没有借阅记录");
            }

            // 3. 检查是否已经归还
            if (existingBorrower.getReturnTime() != null) {
                log.error("图书已经归还 - 图书编号: {}, 归还时间: {}", 
                    existingBorrower.getBookCode(), existingBorrower.getReturnTime());
                return Result.error("该图书已经归还");
            }

            // 4. 设置归还时间
            borrower.setReturnTime(LocalDateTime.now());
            
            // 5. 处理归还逻辑
            borrowerService.returnBook(borrower);
            log.info("借阅记录更新成功 - 借阅人: {}, 图书编号: {}, 归还时间: {}", 
                    borrower.getBorrowerName(), borrower.getBookCode(), borrower.getReturnTime());

            // 6. 更新图书状态
            Book book = bookService.selectByCode(borrower.getBookCode());
            if (book != null) {
                bookService.updateByCodes(book, borrower.getBookCode());
                log.info("图书状态已更新 - 图书编号: {}, 状态: 未借出", book.getBookCode());
            }
            return Result.success();
        } catch (Exception e) {
            log.error("图书归还失败: {}", e.getMessage(), e);
            // 手动标记事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.error("图书归还失败: " + e.getMessage());
        }
    }
}
